<!-- 学社 - 服务 - 服务记录 -->
<template>
  <view>
    <z-navbar title="服务记录" :border-bottom="true" bg-color="#F4AE20"></z-navbar>
    <view class="px-4 pt-5">
      <view class="shadow-card pb-3 flex flex-col justify-center items-center">
        <view class="c-#333 text-34 font-bold mb-1">{{ state.detailData?.service_info?.name }}</view>
        <view class="c-#999 text-20 w-full text-center text-single">（{{ state.detailData?.service_info?.desc }}）</view>
      </view>
      <view class="mt-4 mb-5">
        <!-- 标签栏 -->
        <!-- TODO:当前服务未完成不可切换后面的tab -->
        <u-tabs :list="state.tabList" v-model="state.tabCurrent" font-size="32" active-color="#F4AF22"
          inactive-color="#999" bar-width="30" gutter="20" :active-item-style="tabActiveStyle"
          @change="onTabChange"></u-tabs>
      </view>
      <!-- 顾问未提交 view_type 当前查看用户类型:1=顾问,2=管理员、社长 -->
      <template v-if="!state.detailData?.info && state.detailData?.view_type == 1">
        <view class="relative">
          <image class="absolute top-36 left-0 w-28 h-24 z-2 ml-4" src="/static/images/home/ic_edit.png"></image>
          <u-input v-model="state.content" type="textarea" height="450" auto-height placeholder="请输入相关服务说明"
            placeholder-style="color: #999; fontSize: 24rpx" :custom-style="inputStyle" :maxlength="state.maxInputNum" />
          <view class="absolute bottom-30 right-10 z-2 c-#999 text-24">{{ enteredNum }}/{{ state.maxInputNum }}</view>
        </view>
        <view class="mt-4">
          <z-file-upload ref="uploader" width="144" height="144" maxCount="6" />
        </view>
        <!-- 服务时间 -->
        <view class="mt-7 pb-20">
          <view class="mb-4 c-#333 text-32 font-bold">服务时间</view>
          <view class="mb-3 bg-#F6F6F6 rounded-md flex items-center h-68 px-2" @click="state.showStartTimePicker = true">
            <image class="w-28 h-28" src="/static/images/home/ic_date.png"></image>
            <view class="c-#333 text-28 font-bold ml-2">开始时间</view>
            <view class="flex-1 c-#999 text-28 ml-8">{{ state.startTime ?? '请选择开始时间' }}</view>
            <image class="w-24 h-14" src="/static/images/home/ic_arrow_b.png"></image>
          </view>
          <u-picker v-model="state.showStartTimePicker" mode="time" :params="params" confirm-color="#F4AF22"
            @confirm="onDateConfirm('startTime', $event)" />
          <view class="mb-3 bg-#F6F6F6 rounded-md flex items-center h-68 px-2" @click="state.showEndTimePicker = true">
            <image class="w-28 h-28" src="/static/images/home/ic_date.png"></image>
            <view class="c-#333 text-28 font-bold ml-2">结束时间</view>
            <view class="flex-1 c-#999 text-28 ml-8">{{ state.endTime ?? '请选择结束时间' }}</view>
            <image class="w-24 h-14" src="/static/images/home/ic_arrow_b.png"></image>
          </view>
          <u-picker v-model="state.showEndTimePicker" mode="time" :params="params" confirm-color="#F4AF22"
            @confirm="onDateConfirm('endTime', $event)" />
        </view>
      </template>
      <template v-if="!state.detailData?.info && state.detailData?.view_type == 2">
        <view class="flex flex-col items-center">
          <image class="w-368 h-368 mt-24 mb-8" src="/static/images/empty/img_empty_service.png" />
          <view class="c-#333 text-28">还没有邀请顾问上门服务哦~ </view>
        </view>
      </template>
      <!-- 已提交 -->
      <template v-else>
        <view class="pb-20">
          <!-- 内容 -->
          <view v-if="info" class="flex justify-center items-center mx-auto bg-#F5F5F5 px-3 h-72 rounded-2xl mb-5 ">
            <view class="c-#333 text-24">{{ dateFormat(state.detailData?.info?.start_time, 'YYYY年MM月DD日 HH:mm') }}</view>
            <view class="relative h-full flex items-center">
              <view class="time-gap absolute z-2 c-#999 text-20">
                {{ formatDateDuration(state.detailData?.info?.start_time, state.detailData?.info?.end_time) }}
              </view>
              <u-line color="#C4C4C4" :hair-line="false" border-style="dashed" length="80" margin="0 16rpx"></u-line>
            </view>
            <view class="c-#333 text-24">{{ dateFormat(state.detailData?.info?.end_time, 'YYYY年MM月DD日 HH:mm') }}</view>
          </view>
          <view v-if="info" class="shadow-card p-4">
            <view class="flex justify-between items-center">
              <view class="c-#333 text-28 font-bold">服务内容</view>
              <view class="c-#666 text-28">顾问<text class="c-#F4AF22 ml-1" @click="toHomePage(state.detailData?.info?.counselor?.id)">{{ state.detailData?.info?.counselor?.nickname
              }}</text></view>
            </view>
            <u-line color="#F6F6F6" :hair-line="false" margin="20rpx 0"></u-line>
            <view class="c-#666 text-sm mb-2">{{ state.detailData?.info?.content }}</view>
            <!-- <u-image width="100%" height="352" border-radius="10" src="https://cdn.uviewui.com/uview/swiper/1.jpg" /> -->
            <u-image v-if="isSingleImg(state.detailData?.info?.slideshow)" border-radius="10" width="100%" height="352"
              :src="state.detailData?.info?.slideshow[0]"
              @click="previewImage(state.detailData?.info?.slideshow, 0)"></u-image>
            <view v-else class="grid grid-cols-3 gap-3">
              <u-image width="196" height="196" border-radius="16"
                v-for="(answerImg, answerIndex) in state.detailData?.info?.slideshow" :key="answerIndex" :src="answerImg"
                @click="previewImage(state.detailData?.info?.slideshow, index)" />
            </view>
          </view>
          <view v-if="reply_list">
            <view v-for="(reply, replyIndex) in reply_list" :key="replyIndex">
              <!-- 回复 -->
              <view class="mt-4" v-if="reply.type == 1">
                <view class="c-#333 text-32 font-bold"><text class="c-#F4AF22" @click="toHomePage(reply.user?.id)">{{ reply.user?.nickname }}</text><text
                    class="mx-2">回复</text><text>{{ state.detailData?.info?.counselor?.nickname }}</text></view>
                <view class="c-#666 text-sm mt-3 mb-2">{{ reply.content }}</view>
                <view class="flex flex-wrap">
                  <u-image v-for="(item, index) in reply.slideshow" :key="index" width="136" height="136"
                    border-radius="12" :src="item" class="mr-2" @click="previewImage(reply.slideshow, index)" />
                </view>
                <view class="c-#999 text-24 mt-2">{{ reply.createtime }}</view>
              </view>
              <!-- <u-line color="#F6F6F6" :hair-line="false" margin="20rpx 0"></u-line> -->
              <!-- 顾问建议 -->
              <view v-if="reply.type == 2">
                <view class="c-#333 text-32 font-bold">顾问建议</view>
                <view class="c-#666 text-sm mt-3 mb-2 text-wrap">{{ reply.content }}</view>
                <view class="flex flex-wrap">
                  <u-image v-for="(item, index) in reply.slideshow" :key="index" width="136" height="136"
                    border-radius="12" :src="item" class="mr-2" @click="previewImage(reply.slideshow, index)" />
                </view>
                <view class="c-#999 text-24 mt-2">{{ reply.createtime }}</view>
              </view>
              <u-line color="#F6F6F6" :hair-line="false" margin="20rpx 0"></u-line>
            </view>
          </view>
          <!-- 服务评价 -->
          <view v-if="info && info.comment_content">
            <view class="flex items-center c-#333 text-32 font-bold">
              <view class="mr-4">服务评价</view>
              <view class="flex items-center">
                <image v-for="(item, index) in info.comment_star" :key="index" class="w-80 h-80"
                  :src="`/static/images/home/ic_rate_${index}.png`"></image>
                <image v-for="(item, index) in (5 - info.comment_star)" :key="index" class="w-80 h-80"
                  src="/static/images/home/ic_rate_default.png"></image>
              </view>
            </view>
            <view class="c-#666 text-sm mt-3">{{ info.comment_content }}</view>
          </view>
        </view>
      </template>
    </view>
    <!-- 顾问操作按钮 服务结束无按钮 -->
    <view v-if="service_log && service_log[Number(state.tabCurrent) + 1] != 2 && state.detailData?.view_type == 1"
      class="bottom-wrap-16 bg-white">
      <u-line color="#eee" />
      <view class="btn-submit" @click="onAdviseSubmit">{{ isCurrentSubmit() ? '发布建议' : '提交服务信息' }}</view>
    </view>
    <!-- 社长/管理操作按钮 服务进行中显示 -->
    <view v-if="info && service_log && service_log[Number(state.tabCurrent) + 1] == 1 && state.detailData?.view_type == 2"
      class="bg-white bottom-wrap-16">
      <u-line color="#eee" />
      <view class="flex justify-center">
        <view class="btn-add w-330"
          @click="navigate(`/package_society/pages/service/reply?navTitle=回复顾问&btnName=发布回复&placeholder=请编辑对顾问的回复内容&diagnosis_id=${info && info.id}`)">
          回复顾问
        </view>
        <view class="btn-submit w-330 mr-0"
          @click="navigate(`/package_society/pages/service/finish?diagnosis_id=${info && info.id}`)">结束服务</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { dateFormat } from '@/common/util/date'
import { navigate, showToast, previewImage } from '@/common/util/uni';
import { toHomePage } from "@/common/util/util";
import { getDirectorsDetail, postDirectorsInitiate } from '@/common/http/module/society.js'
import dayjs from 'dayjs'

const uploader = ref()
const state = reactive({
  club_id: '', // 学社id
  service_id: '', // 服务id,
  member_position: '', // 登录用户在该学社身份
  service_num: 0, // 服务总次数 tab总数
  detailData: null, // 服务详情数据
  service_log: null, // 服务记录
  tabCurrent: '',
  tabList: [],
  content: '',
  startTime: '',
  endTime: '',

  score: 4, // 评分
  userType: 0, // 0-社长 1-管理员 2-顾问
  isSubmit: true, // 当前记录是否已提交
  isOver: false, // 是否结束

  showStartTimePicker: false,
  showEndTimePicker: false,

  maxInputNum: 200,

});

const enteredNum = computed(() => {
  return state.content.length > 200 ? 200 : state.content.length
})

const tabActiveStyle = {
  color: '#333333'
}
const inputStyle = {
  backgroundColor: '#F5F5F5',
  padding: '32rpx 32rpx 32rpx 70rpx',
  borderRadius: '12rpx'
}
const params = {
  year: true,
  month: true,
  day: true,
  hour: true,
  minute: true,
  second: false
}

// 完成次数
const finishCount = computed(() => {
  let count = 0
  for (let key in state.detailData.service_log) {
    if (state.detailData.service_log[key] != 2) {
      count = key
      break
    }
  }
  return count == 0 ? count : count - 1
})
// 诊断信息
const info = computed(() => state.detailData && state.detailData.info)
// 回复建议信息
const reply_list = computed(() => state.detailData && state.detailData.reply_list)
// 服务记录
const service_log = computed(() => state.detailData && state.detailData.service_log)

// 判断当次诊断是否提交
function isCurrentSubmit() {
  if (state.detailData) {
    const currentStatus = state.detailData.service_log[Number(state.tabCurrent) + 1]
    return currentStatus == 1
  }
}

function isFinish(index) {
  return service_log.value[Number(index)] == 2 || (Number(index)) <= finishCount.value ? true : false
}

// 格式化服务起止时间时长
function formatDateDuration(startTime, endTime) {
  if (startTime && endTime) {
    const start = dayjs(startTime)
    const end = dayjs(endTime)
    const hours = end.diff(start, 'hour')
    return `${hours}H`
  }
}

function isSingleImg(imgList) {
  if (info && imgList) {
    return imgList && imgList.length == 1
  }
}

// 标签栏切换事件
function onTabChange(index) {
  if (isFinish(index)) {
    state.tabCurrent = index
  } else {
    showToast('未完成上一次服务，不可发起下一次服务~', 'error')
    state.tabCurrent = finishCount.value
  }
  console.log(state.tabCurrent, "kkk")
  // 刷新数据
  loadData()
}

function onDateConfirm(type, e) {
  const { year, month, day, hour, minute } = e
  state[type] = `${year}-${month}-${day} ${hour}:${minute}`
}

function onAdviseSubmit() {
  if (isCurrentSubmit()) {
    // 跳转发布建议
    navigate(`/package_society/pages/service/reply?navTitle=发布建议&btnName=发布建议&placeholder=对这次服务有什么建议呢？&diagnosis_id=${state.detailData.info && state.detailData.info.id}`)
  } else {
    if (!state.content) {
      showToast('请填写内容', 'error')
      return
    }
    if (!state.startTime || !state.endTime) {
      showToast('请选择时间', 'error')
      return
    }
    const images = uploader.value.getUploadedList()
    // 提交诊断
    postDirectorsInitiate({
      club_id: state.club_id,
      service_id: state.service_id,
      content: state.content,
      slideshow: images.map(v => v.url).join(','),
      start_time: state.startTime,
      end_time: state.endTime,
    }).then(() => {
      showToast('提交成功')
      loadData()
    })
  }
}

// 获取服务详情
async function loadData() {
  const { data } = await getDirectorsDetail(state.club_id, state.service_id, Number(state.tabCurrent) + 1)
  state.detailData = data
  state.service_log = data.service_log
}

onLoad(options => {
  state.club_id = options.club_id ?? ''
  state.service_id = options.service_id ?? ''
  state.member_position = options.member_position ?? ''
  // 当前服务下标
  state.service_num = options.service_num ?? ''

  for (let i = 1; i <= options.number; i++) {
    state.tabList.push({ name: `第${i}次` })
  }

  state.tabCurrent = state.service_num == 0 ? 0 : state.service_num - 1
  console.log(state.tabCurrent, "state")
  loadData()
})

defineExpose({ loadData })
</script>

<style lang="scss" scoped>
.shadow-card {
  border-radius: 12rpx;
  box-shadow: -1.2246468525851679e-16px 2px 6px 0px rgba(206, 143, 12, 0.1);
}

.btn-add {
  margin-top: 12rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2rpx solid #F4AF22;
  border-radius: 12rpx;
  color: #F4AF22;
  font-size: 28rpx;
}

.time-gap {
  top: 10rpx;
  left: 50%;
  transform: translateX(-50%);
}

.text-wrap {
	white-space: pre-wrap;
}
</style>
